package com.zcmyth;

import java.util.ArrayList;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

/*
 http://download.oracle.com/javase/7/docs/api/java/lang/Thread.html

 Runnable void run()
 Callable<T> T call()


 */

public class MultiThread {
  public static void main(String[] args) {
    case2();
  }

  public static int num = 0;
  public static Object o = new Object();

  public static void case1() {
    ArrayList<Thread> list = new ArrayList<Thread>();
    for (int i = 0; i < 100; i++) {
      Thread t = new Thread(new Runnable() {
        synchronized public void run() {
          try {
            Thread.sleep(1000);
            System.out.println(num++);
          } catch (Exception e) {

          }
        }
      });
      list.add(t);
    }

    for (Thread t : list)
      t.start();
  }

  public static void case2() {
    ArrayList<Future<Integer>> list = new ArrayList<Future<Integer>>();
    ExecutorService pool = Executors.newCachedThreadPool();
    for (int i = 0; i < 100; i++) {
      try {
        Future<Integer> f = pool.submit(new Callable<Integer>() {
          public Integer call() {
            {
              num++;
              try {
                Thread.sleep(2);
              } catch (Exception e) {
              }
              return num;
            }
          }
        });

        list.add(f);
      } catch (Exception e) {
      }
    }

    for (Future<Integer> t : list) {
      try {
        System.out.println(t.get());
      } catch (Exception e) {
        System.out.println(e);
      }
    }
    pool.shutdown();
  }
}